package com.huiquan.portal.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.huiquan.analysis.domain.User;
import com.huiquan.foundation.constant.RoleID;
import com.huiquan.foundation.constant.SubmitStatus;
import com.huiquan.foundation.util.BusinessUtil;
import com.huiquan.framework.utils.DateUtils;
import com.huiquan.onlineTime.service.OnlineTimeRecordService;

/**
 * @ClassName: WebLoginCheckInterceptor
 * @Description: 每个请求来时要校验session中是否有用户信息
 * @author xulei
 * @version V1.0 Date 2016年3月10日 10:07:01
 */
public class WebLoginCheckInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private OnlineTimeRecordService onlineTimeRecordService;

	@Value("${pause.flag}")
	private String pauseFlag;
	@Value("${pause.start.time}")
	private String pauseStartTime;
	@Value("${pause.end.time}")
	private String pauseEndTime;
	@Value("${system.env.sign}")
	private String systemEnvSign;

	private final Logger LOG = LoggerFactory.getLogger(WebLoginCheckInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
		String timeStr = DateUtils.getTimeStr();
		BusinessUtil.systemEnvSign = systemEnvSign;

		String addr = req.getRemoteAddr();
		// 本机请求直接通过
		boolean localRequest = "0:0:0:0:0:0:0:1".equals(addr) || "127.0.0.1".equals(addr);
		// 局域网内也可以直接通过
		boolean lanRequest = addr.startsWith("172.16.0");
		// 直接通过的是接口，不能是页面
		boolean htmlFlag = req.getServletPath().contains("htm");

		if ((localRequest || lanRequest) && !htmlFlag) {
			return true;
		}

		if ("1".equals(pauseFlag)) { // 开启了夜间暂停访问模式

			// 时间在关闭时间之内
			boolean pauseTime = timeStr.compareTo(pauseStartTime) > 0 && timeStr.compareTo(pauseEndTime) < 0;
			if (pauseStartTime.compareTo(pauseEndTime) > 0) {
				pauseTime = timeStr.compareTo(pauseStartTime) > 0 || timeStr.compareTo(pauseEndTime) < 0;
			}

			if (pauseTime) {
				req.getRequestDispatcher("/WEB-INF/vm/remind.html").forward(req, resp);
				return false;
			}
		}

		// 是否为根路径和登录相关
		boolean beginRequest = req.getRequestURI().equals("/") || req.getRequestURI().indexOf("login") > -1;
		if (beginRequest || req.getRequestURI().equals("/analysis/executeRule/executeRule.do")) {
			// 直接通过的请求
			return true;
		} else {
			User user = (User) req.getSession().getAttribute("user");
			if (user == null) {
				resp.sendRedirect("/login.htm");
				return false;
			}

			// 维护在线时间统计
			if (req.getRequestURI().indexOf("logout") < 0 && !user.getRole().equals(RoleID.ADMIN.getId())) {
				try {
					onlineTimeRecordService.maintain(user, new Date());
				} catch (Exception e) {
					LOG.error("preHandle set online time error, uid=" + user.getUserId());
					e.printStackTrace();
				}
			}

			// session中增加一个list，记录当前系统正在运行的提交功能
			req.getSession().setAttribute("submitList", SubmitStatus.getSubmitRecords());
			return true;
		}
	}
}
